﻿/// <reference path="jquery-1.8.0-vsdoc.js" />
/// <reference path="jhttp://cdnjs.cloudflare.com/ajax/libs/knockout/2.1.0/knockout-min.js" />



$.fn.ms_uiproxy = function () {

	var ms_proxy_mapping = 'ms_proxy_mapping';
	/*
	ms_proxy_to -> source,
			
	*/

	var ctx = this;

	if (!$.inArray(this)) {
		throw 'Invalid data type! Expected array.';
	}

	var instance = {};
	instance.mappers = {};
	instance.link = function () {


		$.map(ctx.toArray(), function (n) {

			//Declare variables for proxy
			var mapping = {
				sourceId: null,
				proxyAttr: null,
				sourceAttr: null,
				custom: null
			};
			$.extend(mapping, eval('(' + $(n).attr(ms_proxy_mapping) + ')'));
			var iProxyId = '#' + $(n).attr('id');
			var iSourceId = mapping.sourceId;
			var iProxyAttr = mapping.proxyAttr;
			var iSourceAttr = mapping.sourceAttr;
			var iCustom = mapping.custom;
			var iNodeName = $(mapping.sourceId).prop('nodeName');
			var iType = $(mapping.sourceId).attr('type');

			//Link object
			if (iNodeName == 'INPUT' && (iType == 'checkbox' || iType == 'radio')) {

				$(iProxyId).prop('checked', $(iSourceId).prop('checked'));

				//Assign checked value
				$(iProxyId).change(function () {
					$(iSourceId).prop('checked',
								$(this).prop('checked')
							);
				});

				$(iSourceId).change(function () {
					$(iProxyId).prop('checked',
								$(this).prop('checked')
							);
				});

			}
			else if (iNodeName == 'SELECT') {

				$(iSourceId).children().clone().appendTo(iProxyId);
				$(iProxyId).linkBoth(iSourceAttr, iSourceId, iProxyAttr);

			}
			else if (iNodeName == 'TABLE') {


			}
			else {

				$(n).val($(iSourceId).val());
				$(iProxyId).linkBoth(iSourceAttr, iSourceId, iProxyAttr);

			}

			if (iCustom != null) {
				//call customize function fn(source,proxy);
				iCustom($(iSourceId)[0], $(iProxyId)[0]);
			}

			//Link event
			/*
			Support button
			*/


		})






	}


	return instance;

};